// feature hien tai khi nguoi dung select trong moi action
var featureCurrentAction = null;

Asset_Type =
{
	NONE: 0,
	DIEMCAPPHEP: 1,
	DIEMVIPHAM: 2,
	QHCHUNG: 3,
	QHCHITIET: 4,
	THUADAT: 5,
	DAYDAN: 6,
	BODEN: 7,
	TRAMBIENAP: 8,
	HOGA: 9,
	TUYENCONG: 10,
	Field_MaDiem: "", // ten truong lay ma diem dau & deim cuoi
	Ma_Diem_Dau : "",
	Loai_Diem_Dau : 0,
	isNew_Diem_Dau : false,
	TimeCode_Diem_Dau: "",
	Ma_Diem_Cuoi : "",
	Loai_Diem_Cuoi : 0,
	isNew_Diem_Cuoi : false,
	TimeCode_Diem_Cuoi: "",
	Line_Obj : null, // luu giu doi tuong tuyen
	
	init: function() {
		return this;
	}
};

STATUS_ASSET=
{
	INSERT: 0,
	UPDATE: 1,
	DELETE: 2
};


var ARRAY_ASSET = function () {	
    this.INPUTs = null;
    this.DATEs = null;
    this.SELECTs = null;
    this.IMGs = null;
    
    this.NUMBERs = null;
    this.COORDINATEs = null;
    this.PKFIELDs = null; // PK field
    this.REQUIREs = null; // require - not pk field
    this.OFFICEs = null; // cac truong hanh chinh va truong bi disabled
    this.BUTTONs = null;
    this.FILES = null; // chua thanh phan de upload document
    this.featureCurrentAction = null;
    this.TypeAsset = Asset_Type.NONE;
    this.COORDINATE = null; // vi tri point hien tai cua tai san
    this.STATUS_ASSET = STATUS_ASSET.UPDATE;
    // ma tru den
    this.MaTruDen = "";
    // ma tai san hien tai duoc chon - dung trong hien thi danh sach
    this.CodeCurrentAsset = ""; 
    // quy hoach
    this.loadAll = true; // load tat ca vung quy hoach
    this.aObjQuyhoachActive = null; // quy hoach dc active
	this.MaVungQHChungField = 'mavungquyhoachchung';
	this.MaVungQGChitietField = 'mavungquyhoachchitiet';
    this.MaQHChung = "";
    this.MaQHChiTiet = "";
    this.NumFeatureQHChung = 0; // so luong feature qh chung
    this.NumFeatureQHChiTiet = 0; // so luong feature qh chi tiet
    this.AttrInfoQH = [];
    this.AttrInfoQHChung = [];
    this.AttrInfoQHChiTiet = [];
    // alias name
    this.AliasName = [];
    // layName
    this.layerName = '';
    this.fieldsetID = ''; // fieldset chua noi dung cua tung tai san
    this.divAssetID = ''; // the div chua noi dung cua fieldset
    
    this.loadQHToZoom = false; // xet xem vung quy hoach da dc load chua thi se zoom
    
    // thong tin feature thua dat khi cap nhat diem vi pham & diem cap phep
    this.feaThuadat = null;

    // ko cho nhập ký tự đặc biệt va chữ tiếng việt
    this.txtKeyDownSpecialChar = function(e) {
		if(this.PKFIELDs == null) return;
		var event = e;
		if(event.shiftKey)
		{
			// ko cho nhap ky tu dac biet
			if ((event.keyCode < 65 || event.keyCode > 90) 
    				&& (event.keyCode < 97 || event.keyCode > 122)) {
                    event.preventDefault();
                }
			return;
		}
		// Allow: backspace, delete, tab, escape, and enter
    	var event = e;
        if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9
		    || event.keyCode == 27 || event.keyCode == 13 ||
        // Allow: Ctrl+A
		    (event.keyCode == 65 && event.ctrlKey === true) ||
        // Allow: home, end, left, right
		    (event.keyCode >= 35 && event.keyCode <= 39)) {
            // let it happen, don't do anything
            return;
        }
        else
    	{     	
    		if ((event.keyCode < 48 || event.keyCode > 57) 
    				&& (event.keyCode < 65 || event.keyCode > 90) 
    				&& (event.keyCode < 97 || event.keyCode > 122)) {
                    event.preventDefault();
                }
    	}   
	};

    // key down textbox
    this.txtKeyDown = function (e) {
        // Allow: backspace, delete, tab, escape, and enter
    	var event = e;
        if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9
		    || event.keyCode == 27 || event.keyCode == 13 ||
        // Allow: Ctrl+A
		    (event.keyCode == 65 && event.ctrlKey === true) ||
        // Allow: home, end, left, right
		    (event.keyCode >= 35 && event.keyCode <= 39)) {
            // let it happen, don't do anything
            return;
        }
        // Allow: .
        else if (event.keyCode == 190) {
        	var ua = $.browser;
        	var idElement = "";
        	var ua = $.browser;
            if (!ua.mozilla) idElement = event.srcElement.id;
            else idElement = event.target.id;
            var objElement = document.getElementById(idElement);
            var sText = objElement.value;
            var isDecimal = objElement.getAttribute("IsDecimal");
            if ((sText.indexOf('.') == -1) && (isDecimal == 1)
			    && (sText.length > 0))
                return;
            else
                event.preventDefault();
        } else {
            // Ensure that it is a number and stop the keypress
            if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57)
			    && (event.keyCode < 96 || event.keyCode > 105)) {
                event.preventDefault();
            }
        }
    };

    this.setChangedText_Attribute = function (targetELement) {
        var idElement = "";        
        var ua = $.browser;
        if (!ua.mozilla) idElement = event.srcElement.id;
        else idElement = targetELement.id;
        var objElement = document.getElementById(idElement);
        var value = objElement.value;
        var alias = null;
        var aliasCurrents = arrField_Alias_Current;

    	for(var j=0;j<aliasCurrents.length;j++)
		{
			if(idElement.toLowerCase() == aliasCurrents[j].controlID.toLowerCase())
			{
				alias = aliasCurrents[j];
				break;
			}
		}
    	
        if(alias == null) return;
        bSaveEditting = false;
        var date = null;
        if(alias.Type == 'date')
		{
        	// format: dd/mm/yyyy
            var splitDate = value.split('/');
            var year = parseInt(splitDate[2]);
            var month = parseInt(splitDate[1]);
            var day = parseInt(splitDate[0]);
            if (month < 10) month = "0" + month;
            if (day < 10) day = "0" + day;
            date = year + "-" + month + "-" + day;
		}
        
        // cap nhat thuoc tinh cho quy hoach chi tiet
        if($("#" + idElement).attr("rel_chitiet") != undefined)
    	{
        	var aliasChitiet = null;
        	var idElementChitiet = $("#" + idElement).attr("rel_chitiet");
        	if(alias.Type == 'date') $("#" + idElementChitiet).datepicker('setDate', value);
        	else $("#" + idElementChitiet).val(value);
        	for(var j=0;j<assetQHCHITIET.AliasName.length;j++)
			{
				if(idElementChitiet.toLowerCase() == assetQHCHITIET.AliasName[j].controlID.toLowerCase())
				{
					aliasChitiet=assetQHCHITIET.AliasName[j];
					break;
				}
			}
	        if(aliasChitiet==null) return;
	        bSaveEditting = false;
	        if(alias.Type == 'date') assetQHCHITIET.AttrInfoQH[aliasChitiet.Name] = date;
	        else assetQHCHITIET.AttrInfoQH[aliasChitiet.Name] = value;
	        if(featureCurrentAction!= null)
        	{
        		var valueObj = value;
        		if(alias.Type == 'date') valueObj = date;
                if (featureCurrentAction.feature) {
                    featureCurrentAction.feature.attributes[alias.Name] = valueObj;
                } else {
                    featureCurrentAction.attributes[alias.Name] = valueObj;
                }	
        	}
    	}
        else
    	{
        	if(featureCurrentAction!= null)
    		{
        		var valueObj = value;
        		if(alias.Type == 'date') valueObj = date;
                if (featureCurrentAction.feature) {
                    featureCurrentAction.feature.attributes[alias.Name] = valueObj;
                } else {
                    featureCurrentAction.attributes[alias.Name] = valueObj;
                }	
    		}
    	}
    };
    
    this.setChangedComboBox_Attribute = function(targetELement)
    {
    	var idElement = "";
    	var ua = $.browser;
        if (!ua.mozilla) idElement = event.srcElement.id;
        else idElement = targetELement.id;
        if(idElement == undefined) idElement = targetELement.id;
        var objElement = document.getElementById(idElement);
    	var value = objElement[objElement.selectedIndex].value;
        var alias = null;
        var aliasCurrents = null;
        var asset = tabsQuyHoachObj.getVungQuyHoach();
        if(tabsQuyHoachObj.typeQuyhoachActive == 0) 
    	{
        	aliasCurrents = arrField_Alias_Current;
        	if(aliasCurrents.length == 0) aliasCurrents = asset.AliasName;
    	}
        else aliasCurrents = asset.AliasName;
        
    	for(var j=0;j<aliasCurrents.length;j++)
		{
			if(idElement.toLowerCase() == aliasCurrents[j].controlID.toLowerCase())
			{
				alias = aliasCurrents[j];
				break;
			}
		}
        
        if(alias==null) return;
    	bSaveEditting = false;
    	if(featureCurrentAction != null)
		{
            featureCurrentAction.attributes[alias.Name] = value;
		}
    	asset.AttrInfoQH[alias.Name] = value; 	
    	
        if($(objElement).attr('type') == 'hanhchinh')
    	{
        	var idChild = $(objElement).attr('child');
        	getPhuongXa_From_QuanHuyen(idElement, idChild);
    	}
        // quy hoach chung
        if(tabsQuyHoachObj.typeQuyhoachActive == 1)
    	{
        	assetQHCHITIET.AttrInfoQH[alias.Name] = value;
    	}
    };
    
    this.setChangedQHChiTiet_MaQHChung = function()
    {
    	var sFieldMaQHChung = assetQHCHITIET.MaVungQHChungField;
    	var idElement = "";
    	var ua = $.browser;
        if (!ua.mozilla) idElement = event.srcElement.id;
        else idElement = targetELement.id;
        var objElement = document.getElementById(idElement);
    	var value = objElement[objElement.selectedIndex].value;
    	bSaveEditting = false;
        featureCurrentAction.attributes[sFieldMaQHChung] = value;
        $("#txt_QHCHITIET_QHChung").val(value);
        // cap nhat ma qh chung cho qh chi tiet
        assetQHCHITIET.AttrInfoQH[sFieldMaQHChung] = value;
    };
    
    this.checkPK = function(objAsset, typeAsset, targetELement) {
    	var bExists = false;
    	if (featureCurrentAction == null) {
    		return false;
    	}
		if (featureCurrentAction.layer == null) {
			//alert("Feature current null");
			return false;
		}
    	var idElement = "";
    	var ua = $.browser;
        if (!ua.mozilla) idElement = event.srcElement.id;
        else idElement = targetELement.id;
        var alias = null;
    	var indexLayer = -1;
    	var layerAsset = null;
        var asset = tabsQuyHoachObj.getVungQuyHoach();
        var aliasCurrents = null;
        if(tabsQuyHoachObj.typeQuyhoachActive == 0) 
    	{
        	aliasCurrents = arrField_Alias_Current;
        	indexLayer = LayerTool.getIndexLayer();
    	}
        else 
    	{
        	aliasCurrents = asset.AliasName;
     		// lay layer
     		var objVectorLayer = LayerTool.getVectorLayer(asset.layerName);
     		indexLayer = objVectorLayer.IndexLayer;
    	}        
        for(var j=0;j<aliasCurrents.length;j++)
		{
			if(idElement.toLowerCase() == aliasCurrents[j].controlID.toLowerCase())
			{
				alias = aliasCurrents[j];
				break;
			}
		}
        
        // lay lop ban do
 		layerAsset = map.layers[indexLayer];   
        if(alias == null) 
        {
    		alert("alias null");
    		return false;
    	} 	   	
    	var feature = null;
    	/// point
    	if(vectorArray[indexLayer].Geometry_Type.toLowerCase() == Geometries.Point) 
		{
    		var iTotal = 0; 
        	// ko lay feature cuoi cung - la feature dang tao moi
    		if(arrField_Alias_Current.length != 0) iTotal = layerAsset.features.length - 1;
    		else iTotal = layerAsset.features.length;
	    	for(var i=0; i < iTotal; i++)
	    	{
	    		feature = layerAsset.features[i];
	    		if(feature.attributes[alias.Name] == undefined) continue;
        		if($("#"+idElement).val().toLowerCase() == feature.attributes[alias.Name].toLowerCase())
        		{
        			bExists = true;
        			break;
        		}		
	    	}
		}
    	// polyline
    	else if(vectorArray[indexLayer].Geometry_Type.toLowerCase() == Geometries.Polyline)
		{
    		// loai bo cac vertext - dang point
    		var featuresLine = [];
    		for(var i=0; i < layerAsset.features.length - 1; i++)
	    	{
    			if(layerAsset.features[i].geometry.CLASS_NAME != "OpenLayers.Geometry.MultiLineString") continue;
    			featuresLine[featuresLine.length] = layerAsset.features[i];
	    	}

        	// ko lay feature cuoi cung - la feature dang tao moi
    		if(arrField_Alias_Current.length != 0) iTotal = featuresLine.length - 1;
    		else iTotal = featuresLine.length;
    		for(var i=0; i < iTotal; i++)
	    	{
	    		feature = featuresLine[i];
	    		if(feature.attributes[alias.Name] == undefined) continue;
        		if($("#"+idElement).val().toLowerCase() == feature.attributes[alias.Name].toLowerCase())
        		{
        			bExists = true;
        			break;
        		}	
	    	}
		}
    	else // polygon
		{
    		// loai bo cac vertext - dang point
    		var featuresPolygon = [];
    		for(var i=0; i < layerAsset.features.length - 1; i++)
	    	{
    			if(layerAsset.features[i].geometry.CLASS_NAME != "OpenLayers.Geometry.MultiPolygon") continue;
    			featuresPolygon[featuresPolygon.length] = layerAsset.features[i];
	    	}

        	// ko lay feature cuoi cung - la feature dang tao moi
    		if(arrField_Alias_Current.length != 0) iTotal = featuresPolygon.length - 1;
    		else iTotal = featuresPolygon.length;
    		for(var i=0; i < featuresPolygon.length - 1; i++)
	    	{
	    		feature = featuresPolygon[i];
	    		if(feature.attributes[alias.Name] == undefined) continue;
        		if($("#"+idElement).val().toLowerCase() == feature.attributes[alias.Name].toLowerCase())
        		{
        			bExists = true;
        			break;
        		}  		
	    	}    		
		}
    	if(bExists)
    	{
    		alert("Ma ton tai");
    		$("#"+idElement).focus();
    		for(var i=0; i<objAsset.BUTTONs.length; i++)
			{
    	    	$(objAsset.BUTTONs[i]).attr('disabled', true);
			}
    	}
    	else
    	{
    		for(var i=0; i<objAsset.BUTTONs.length; i++)
			{
    	    	$(objAsset.BUTTONs[i]).attr('disabled', false);
			}
    	}
    };

    this.checkPKQHChung = function() {
		var layerQHChungName = assetQHCHUNG.layerName;
		var layerQHChung = null;
        var i = 0;
        for(i=0;i<vectorArray.length;i++)
    	{
        	var vectorItem = vectorArray[i];
        	if(layerQHChungName.toLowerCase() == vectorItem.LayerId.toLowerCase() && !vectorItem.Map_Service)
    		{
        		layerQHChung = map.layers[vectorItem.IndexLayer];
        		break;
    		}
    	}
		if(layerQHChung == null) return;
		var idElement = "";
    	var ua = $.browser;
        if (!ua.mozilla) idElement = event.srcElement.id;
        else idElement = targetELement.id;
        var objValue = $("#"+idElement).val();
        var feature = 0;
        var arrFeatures = layerQHChung.features;
        for(i=0; i<arrFeatures.length; i++)
    	{
        	feature = arrFeatures[i];
        	var objMaQH = feature.attributes[assetQHCHUNG.MaVungQHChungField];
        	if(objValue.toLowerCase() == objMaQH.toLowerCase())
    		{
        		/** fill data - phong toi ban do quy hoach chung ***/
        		trvBandoQuyHoach.layerQHChung = layerQHChung;
        		trvBandoQuyHoach.assetQHChung = assetQHCHUNG;
         		var arrFeaturQHChung = trvBandoQuyHoach.layerQHChung.getFeaturesByAttribute(trvBandoQuyHoach.assetQHChung.MaVungQHChungField, objMaQH);
         		var feature = arrFeaturQHChung[0];
         		trvBandoQuyHoach.assetQHChung.AttrInfoQH = [];
         		if(feature != undefined)
        		{
        	 		for (i = 0; i < trvBandoQuyHoach.assetQHChung.AliasName.length; i++){
        	 			var sControlID = trvBandoQuyHoach.assetQHChung.AliasName[i].controlID;
        	 			var objValue = feature.attributes[trvBandoQuyHoach.assetQHChung.AliasName[i].Name];
        	 			if(trvBandoQuyHoach.assetQHChung.AliasName[i].Type == 'date' && objValue != undefined)
        				{
        	 				// format: yyyy-mm-dd
        	 				objValue = objValue.split('-');
        	 				if(objValue.length == 3)
        					{
        		 				// format: dd/mm/yyyy
        		 				objValue = objValue[2] + '/' + objValue[1] + '/' + objValue[0];
        		 				$('#' + sControlID).datepicker('setDate', objValue);
        					}
        				}
        	 			else $('#' + sControlID).val(objValue);
        	 			trvBandoQuyHoach.assetQHChung.AttrInfoQH[trvBandoQuyHoach.assetQHChung.AliasName[i].Name] = objValue;
        	 		}	 			
        		}
         		
        		break;
    		}
    	}
	};
    
    this.init = function (objAsset) {
    	if(this.INPUTs != null)
		{
	        for (var i = 0; i < this.INPUTs.length; i++) {
	            var $target = $(this.INPUTs[i]);
	            //$target.attr('disabled', false);
	            //$target.val("");
	            if ($target != undefined) {
	                $target.change(function (e) {
	                	var targetELement = e.target;
	                    objAsset.setChangedText_Attribute(targetELement);
	                });
	            }
	        }
		}

    	if(this.PKFIELDs != null)
		{
	        for(var i = 0; i<this.PKFIELDs.length; i++) {
	        	var $target = $(this.PKFIELDs[i]);
	        	$target.removeClass("td_Input");
	            if ($target != undefined) {
					$target.blur(function(e) {
						var targetELement = e.target;
						objAsset.checkPK(objAsset, objAsset.TypeAsset, targetELement);
					});
	                $target.change(function(e) {     
	                	var targetELement = e.target;
	                    objAsset.setChangedText_Attribute(targetELement);
	                });
	                
	                $target.keydown(function (e) {
	                	var targetELement = e;
	                	objAsset.txtKeyDownSpecialChar(targetELement);
	                });
	            }
	        }     
		}

    	if(this.REQUIREs != null)
		{
	        for(var i = 0; i<this.REQUIREs.length; i++) {
	        	var $target = $(this.REQUIREs[i]);
	        	$target.removeClass("td_Input");
	        }    
		}
        
		// lay thong tin cac truong hanh chinh
    	if(this.OFFICEs != null)
		{
			for(i=0;i<this.OFFICEs.length;i++)
			{
				$objPKFIELDs = $(this.OFFICEs[i]);
				$objPKFIELDs.attr('disabled', true);    			
			}
		}

    	if(this.SELECTs != null)
		{
	        for(var i = 0; i<this.SELECTs.length; i++) {
	        	var $target = $(this.SELECTs[i]);
	            //$target.val("");
	            if($target.length > 0) 
	        	{
	            	$target.change(function(e){
	                	var targetELement = e.target;
	            		objAsset.setChangedComboBox_Attribute(targetELement);
	            	});
	        	}
	        }
		}

    	if(this.DATEs != null)
		{
	        for (var i = 0; i < this.DATEs.length; i++) {
	            var $target = $(this.DATEs[i]);
	            //$target.val("");
	            $target.change(function (e) {
	            	var targetELement = e.target;
	                objAsset.setChangedText_Attribute(targetELement);
	            });
	            $target.datepicker({
	                numberOfMonths: 1,
	                constrainInput: true,
	                dateFormat: 'dd/mm/yy',
	                showButtonPanel: false,
	                hideIfNoPrevNext: true,
	                autoSize: false,
	                onSelect: function (dateValue) {
	                	// format: dd/mm/yyyy
	                    var splitDate = dateValue.split('/');
	                    var year = parseInt(splitDate[2]);
	                    var month = parseInt(splitDate[1]);
	                    var day = parseInt(splitDate[0]);
	                    if (month < 10) month = "0" + month;
	                    if (day < 10) day = "0" + day;
	                    var date = year + "-" + month + "-" + day;
	                    var idElement = this.id;
	                    if(idElement == 'txt_QHCHUNG_TGBD')
	                	{
	                    	$('#txt_QHCHUNG_NamQH').val(year);
	                    	$('#txt_QHCHITIET_NamQH').val(year);                    	
	                    	assetQHCHUNG.AttrInfoQH["namquyhoach"] = parseInt(year);	
	                    	assetQHCHITIET.AttrInfoQH["namquyhoach"] = parseInt(year);
	                	}
	                    if(idElement == 'txt_QHCHITIET_TGBD')
	                	{
	                    	$('#txt_QHCHITIET_NamQH').val(year);   
	                    	assetQHCHITIET.AttrInfoQH["namquyhoach"] = parseInt(year);                 	
	                	}
	                    var alias = null;                
	                    var aliasCurrent = null;
	                    // quy hoach chung
	                    if(tabsQuyHoachObj.typeQuyhoachActive == 1) aliasCurrent = assetQHCHUNG.AliasName;
	                    // quy hoach chi tiet
	                    else if(tabsQuyHoachObj.typeQuyhoachActive == 2) aliasCurrent = assetQHCHITIET.AliasName;
	                    // ko phai lop quy hoach
	                    else aliasCurrent = arrField_Alias_Current;
	                    
	                    for(var j=0;j<aliasCurrent.length;j++)
	            		{
	            			if(idElement.toLowerCase() == aliasCurrent[j].controlID.toLowerCase())
	            			{
	            				alias = aliasCurrent[j];
	            				break;
	            			}
	            		}
	                    if(alias == null) return;
	                    var asset = tabsQuyHoachObj.getVungQuyHoach();
	                    asset.AttrInfoQH[alias.Name] = date;
	                    // cap nhat thuoc tinh cho quy hoach chi tiet
	                    if($(this).attr("rel_chitiet") != undefined)
	                	{
	                    	var aliasChitiet = null;
	                    	var idElementChitiet = $(this).attr("rel_chitiet");
	                    	$("#" + idElementChitiet).datepicker('setDate', dateValue);
	                    	for(var j=0;j<assetQHCHITIET.AliasName.length;j++)
	            			{
	            				if(idElementChitiet.toLowerCase() == assetQHCHITIET.AliasName[j].controlID.toLowerCase())
	            				{
	            					aliasChitiet=assetQHCHITIET.AliasName[j];
	            					break;
	            				}
	            			}
	            	        if(aliasChitiet==null) return;
	            	        bSaveEditting = false;
	            	        if(alias.Type == 'date') assetQHCHITIET.AttrInfoQH[aliasChitiet.Name] = date;
	            	        else assetQHCHITIET.AttrInfoQH[aliasChitiet.Name] = value;
	            	        if(featureCurrentAction!= null)
	                    	{
	                            if(featureCurrentAction != null)
	                        	{
	                                featureCurrentAction.attributes[alias.Name] = date;
	                        	}
	                    	}
	                	}
	                    else
	                	{
	                        if(featureCurrentAction != null)
	                    	{
	                            featureCurrentAction.attributes[alias.Name] = date;
	                    	}
	                	}
	                }
	            });
	        }
        }

        for (var i = 0; i < this.NUMBERs.length; i++) {
            var $target = $(this.NUMBERs[i]);
            $target.keydown(function (e) {
            	var targetELement = e;
                objAsset.txtKeyDown(targetELement);
            });
            $target.change(function (e) {
            	var targetELement = e.target;
                objAsset.setChangedText_Attribute(targetELement);
            });
        }
        
        this.disabledFiles();        
    };
    
    // ham add feature point tu toa do x - y 
    this.CoordinateChanged_Point = function()
    {
    	var idElement = "";
    	var ua = $.browser;
        if (!ua.mozilla) idElement = event.srcElement.id;
        else idElement = targetELement.id;
        var objElement = document.getElementById(idElement);
        var featureCurrent = objElement.feature ;
        if(featureCurrent==null)return;
        var coordinate = objElement.value;
        var x=0, y=0;
        var bChanged = false;
        for(var coor=0; coor<this.COORDINATEs.length; coor++) {
        	var controlID =  this.COORDINATEs[coor].substring(1);
        	if(idElement.toLowerCase() != controlID.toLowerCase()) continue;
        	for(var i=0;i<arrField_Alias_Current.length;i++)
    		{
	        	if(controlID.toLowerCase() == arrField_Alias_Current[i].controlID.toLowerCase()) {
	        		bChanged = true;
	        		switch (arrField_Alias_Current[i].Name.toLowerCase()) {
	    			case "x":
	    				x = parseFloat(coordinate);
	    				y = parseFloat(featureCurrent.geometry.y);
    					var obj = this.COORDINATE["x"];
	    				var bIsIn = isPointInDaNangFromXY(x, y);
	    				if(!bIsIn)
	    				{
	    					alert(LANGUAGE["msg_In_DaNang"]);
	    					$(this.COORDINATEs[coor]).val(obj[0]);
	    					return;
	    				}
	    				featureCurrent.geometry.x = coordinate;
	    				break;
	    			case "y":
	    				x = parseFloat(featureCurrent.geometry.x);
	    				y = parseFloat(coordinate);
    					var obj = this.COORDINATE["y"];
	    				var bIsIn = isPointInDaNangFromXY(x, y);
	    				if(!bIsIn)
	    				{
	    					alert(LANGUAGE["msg_In_DaNang"]);
	    					var obj = this.COORDINATE["y"];
	    					$(this.COORDINATEs[coor]).val(obj[0]);
	    					return;
	    				}
	    				featureCurrent.geometry.y = coordinate;
	    				break;
	        		break;
	        		}
	        	}
    		}
        	if(bChanged) break;
        }
        
        var widthFeature = 5000; 
		var XMin = parseFloat(featureCurrent.geometry.x) - widthFeature;
		var XMax = parseFloat(featureCurrent.geometry.x) + widthFeature;
		
		var heightFeature = 5000;
		var YMin = parseFloat(featureCurrent.geometry.y) - heightFeature;
		var YMax = parseFloat(featureCurrent.geometry.y) + heightFeature;
		var WGSProjection = new OpenLayers.Projection(projection);
		var bounds = new OpenLayers.Bounds(XMin, YMin, XMax, YMax).transform(
				WGSProjection, WGSProjection);
		map.zoomToExtent(bounds);
    	var indexLayer = LayerTool.getIndexLayer();
    	map.layers[indexLayer].redraw();
    	map.layers[indexLayer].refresh();
    };
    
    this.fillDataFromFeatureCurrentPoint = function(assetObj, featureCurrent)
    {    	
    	if(featureCurrent==null)return;
    	//arrTDAttribute = [];
    	var i = 0;
    	// neu tao moi thi lay toa do cua diem dc tao
    	if (actionCurrent == PortletTypeAction.Insert || actionCurrent == PortletTypeAction.InsertCoor 
    			|| actionCurrent == PortletTypeAction.AddLineExtension) {
    		// lay thong tin cac truong
    		for(i=0;i<this.PKFIELDs.length;i++)
    		{
    			$objPKFIELDs = $(this.PKFIELDs[i]);
    			$objPKFIELDs.attr('disabled', false);    			
    		}
    	}
    	else
    	{
    		this.enabledButton();

    		// lay thong tin cac truong
    		for(i=0;i<this.PKFIELDs.length;i++)
    		{
    			$objPKFIELDs = $(this.PKFIELDs[i]);
    			$objPKFIELDs.attr('disabled', true);    			
    		}	
    	}
    	this.enabledFiles();
    	
    	for(i=0;i<arrField_Alias_Current.length;i++)
		{
    		if (arrField_Alias_Current[i].Type == "date") {
    			var inputTextAlias = base.getElementById(arrField_Alias_Current[i].controlID);
    			if(inputTextAlias == null) continue;
    			$date = $("#" + arrField_Alias_Current[i].controlID);
    			$date.datepicker({
    						numberOfMonths : 1,
    						constrainInput : true,
    						dateFormat : 'dd/mm/yy',
    						showButtonPanel : false,
    						hideIfNoPrevNext : true,
    						autoSize : false,
    						onSelect : function(date) {
    							var splitDate = date.split('/');
    							var year = parseInt(splitDate[2]);
    							var month = parseInt(splitDate[1]);
    							var day = parseInt(splitDate[0]);
    							if(month<10) month = "0" + month;
    							if(day<10) day = "0" + day;
    							var date = year + "-" + month + "-" + day;
								featureCurrentAction.attributes[this.attribute] = date;
    						}
    					});
    			
    			if(actionCurrent == PortletTypeAction.Insert || actionCurrent == PortletTypeAction.InsertCoor)
    			{
    				// format: dd/mm/yyyy
    				objValue = $(inputTextAlias).val();
    				objValue = objValue.split('/');
    				if(objValue.lenth == 3)
					{
	    				// format: yyyy-mm-dd
	    				objValue = objValue[2] + '-' + objValue[1] + '-' + objValue[0];
    					featureCurrentAction.attributes[arrField_Alias_Current[i].Name] = objValue;
					}
    			}
    			else
				{
	    			if (featureCurrentAction != null) {
	    				var objValue = null;
    					objValue = featureCurrentAction.attributes[arrField_Alias_Current[i].Name];
	    				if (objValue != undefined) {
	    					var currentTime = objValue;
	    					var splitDate = currentTime.split('-');
	    					var year = parseInt(splitDate[0]);
	    					var month = parseInt(splitDate[1]);
	    					var day = parseInt(splitDate[2]);
	    					currentTime = new Date(year, month, day);
	    					$date.datepicker("setDate", currentTime.getDate() + "/"
	    							+ (currentTime.getMonth()) + "/"
	    							+ currentTime.getFullYear());
	    				}
	    				else
	    				{
	    					$(inputTextAlias).val('');
	    				}
	    			} else {
    					$(inputTextAlias).val('');
	    			}
				}
    			inputTextAlias.attribute = arrField_Alias_Current[i].Name;
    			inputTextAlias.disabled=!arrField_Alias_Current[i].IsEditor;	    			
    		}else if (arrField_Alias_Current[i].Type == "img")
			{  			
    			var idDivPreview = this.IMGs[0];
    			var idForm = this.IMGs[1];
    			var idFileInput = this.IMGs[2];
    			setImg(idForm, idFileInput, idDivPreview, arrField_Alias_Current[i].Name, arrField_Alias_Current[i].IsEditor);
			}
    		else if(arrField_Alias_Current[i].Type == 'file')
			{
    			var files = null;
    			for(var j=0; j<this.FILES.length; j++)
				{
    				files = this.FILES[j];
        			var idForm = files[0];
        			var idFileInput = files[1];
        			var idDivPreview = files[2];
        			if(idFileInput.substr(1,idFileInput.length-1) == arrField_Alias_Current[i].controlID)
    				{
            			setDocument(idForm, idFileInput, idDivPreview, arrField_Alias_Current[i].Name);
    				}	
				}
			}
    		else if (arrField_Alias_Current[i].IsCategory) {    			
    			var objValue_SelectIndex = null;
    			if (featureCurrentAction != null) {
					objValue_SelectIndex = featureCurrentAction.attributes[arrField_Alias_Current[i].Name];
    			}
    			var indexItem = 0;
    			var select_Text_Alias = base.getElementById(arrField_Alias_Current[i].controlID);
    			if(select_Text_Alias == undefined || select_Text_Alias == null) continue;
    			switch (arrField_Alias_Current[i].Name.toLowerCase()) {
    			case "quanhuyen":
				case "maquan":
					if (vectorDistricts != null) {
						var indexLayer = LayerTool.getIndexLayer();
						var bFeature = featureCurrentAction.geometry.bounds;
						var bounds_District = new OpenLayers.Bounds(bFeature.left, bFeature.bottom, bFeature.right, bFeature.top);
						if (vectorArray[indexLayer - numBaseLayer].Geometry_Type == Geometries.Point) {
							var tolerance = 1;
							bounds_District.left -= tolerance;
							bounds_District.right += tolerance;
							bounds_District.top += tolerance;
							bounds_District.bottom -= tolerance;
						}
						// add feature de lay geometry
						createPolygonFromBound(vectorGraphicsClick, bounds_District);
						
						var ii = 0;
						for (ii = 0; ii < arrFeatureDistrict.length; ii++) {
							var featureDistrict = arrFeatureDistrict[ii];
							var bb = featureDistrict.geometry.components[0];
							if (bb.intersects(vectorGraphicsClick.features[0].geometry)) {
								featureCurrentAction.attributes[arrField_Alias_Current[i].Name] = featureDistrict.attributes["dist_id"];
								$(select_Text_Alias).val(featureDistrict.attributes["dist_id"]);
					        	var idChild = $(select_Text_Alias).attr('child');
					        	getPhuongXa_From_QuanHuyen(arrField_Alias_Current[i].controlID, idChild);
								break;
							}
						}
					}
					break;
				case "phuongxa":
				case "maphuong":
					if (vectorCommune != null) {
						var indexLayer = LayerTool.getIndexLayer();
						var bFeature = featureCurrentAction.geometry.bounds;
						var bounds_Commune = new OpenLayers.Bounds(bFeature.left, bFeature.bottom, bFeature.right, bFeature.top);
						if (vectorArray[indexLayer - numBaseLayer].Geometry_Type == Geometries.Point) {
							var tolerance = 1;
							bounds_Commune.left -= tolerance;
							bounds_Commune.right += tolerance;
							bounds_Commune.top += tolerance;
							bounds_Commune.bottom -= tolerance;
						}
						// add feature de lay geometry
						createPolygonFromBound(vectorGraphicsClick, bounds_Commune);
						
						var ii = 0;
						for (ii = 0; ii < arrFeatureCommune.length; ii++) {
							var featureCommune = arrFeatureCommune[ii];							
							var bb = featureCommune.geometry.components[0];
							if (bb.intersects(vectorGraphicsClick.features[0].geometry)) {
								featureCurrentAction.attributes[arrField_Alias_Current[i].Name] = featureCommune.attributes["com_id"];
								$(select_Text_Alias).val(featureCommune.attributes["com_id"]);
								break;
							}
						}
					}
					break;
					default:
						var bSelected = false;
						if(actionCurrent == PortletTypeAction.Insert || actionCurrent == PortletTypeAction.InsertCoor) 
		    			{
		    				objValue = $(select_Text_Alias).val();
	    					featureCurrentAction.attributes[arrField_Alias_Current[i].Name] = objValue;
		    				if(objValue != '') bSelected = true;
		    			}
		    			else
						{
		    				if (featureCurrentAction != null) {
	        					objValue_SelectIndex = featureCurrentAction.attributes[arrField_Alias_Current[i].Name];
		        			}
		    				if(objValue_SelectIndex != undefined)
	    					{
			        			while(select_Text_Alias[indexItem] != null)
			    				{
			        				var option = select_Text_Alias.options[indexItem];
			        				var valueItem = option.getAttribute('value');
			        				if(valueItem == objValue_SelectIndex)
			    					{    					
			        					$(select_Text_Alias).val(valueItem).attr('selected',true);
			        					bSelected = true;
			        			        if(arrField_Alias_Current[i].Name == 'maloaigiayphep') 
			        			        	loaigiayphep_changed();
			    						break;
			    					}
			        				indexItem++;
			    				}
	    					}
		    				else bSelected = false;
						}    			
		    			if(!bSelected) select_Text_Alias.selectedIndex = 0;
						break;
    			}
				select_Text_Alias.attribute = arrField_Alias_Current[i].Name;								
				select_Text_Alias.disabled = !arrField_Alias_Current[i].IsEditor;
    		}
    		else
			{
    			switch (arrField_Alias_Current[i].Name.toLowerCase()) {
    			case "x":
    			case "y":
					var obj = [];
    				if(this.COORDINATE==null) this.COORDINATE = [];
    				var valueCoor = "";
    				if(arrField_Alias_Current[i].Name.toLowerCase() == "x") 
					{
    					valueCoor = featureCurrent.geometry.x;
					}
    				else 
					{
    					valueCoor = featureCurrent.geometry.y;
					}
                    featureCurrentAction.attributes[arrField_Alias_Current[i].Name] = valueCoor;
                    for(var coor=0; coor<this.COORDINATEs.length; coor++) {
                    	var controlID =  this.COORDINATEs[coor].substring(1);
                    	if(controlID.toLowerCase() == arrField_Alias_Current[i].controlID.toLowerCase()) {
                    		$(this.COORDINATEs[coor]).val(valueCoor);
        					obj[0] = valueCoor;
        					obj[1] = this.COORDINATEs[coor];
        					this.COORDINATE[arrField_Alias_Current[i].Name.toLowerCase()] = obj;
                    		break;
                    	}
                    }
                    $(this.COORDINATEs[coor])[0].feature = featureCurrent;
                    if ($(this.COORDINATEs[coor]) != undefined) {
                    	$(this.COORDINATEs[coor]).change(function () {
                    		assetObj.CoordinateChanged_Point();
                        });
                    }
                    break;
				case "diachiip":
					featureCurrentAction.attributes[arrField_Alias_Current[i].Name] = IP_Addr;
					break;
				case "ngaycn":
					var currentTime = new Date();
					var year = currentTime.getFullYear();
					var month = currentTime.getMonth() + 1;
					var day = currentTime.getDate();
					if(month<10) month = "0" + month;
					if(day<10) day = "0" + day;
					var date = year + "-" + month + "-" + day;
					featureCurrentAction.attributes[arrField_Alias_Current[i].Name] = date;
					break;
				case "quanhuyen":
				case "maquan":
					if (vectorDistricts != null) {
						var indexLayer = LayerTool.getIndexLayer();
						var bFeature = featureCurrentAction.geometry.bounds;
						var bounds_District = new OpenLayers.Bounds(bFeature.left, bFeature.bottom, bFeature.right, bFeature.top);
						if (vectorArray[indexLayer - numBaseLayer].Geometry_Type == Geometries.Point) {
							var tolerance = 1;
							bounds_District.left -= tolerance;
							bounds_District.right += tolerance;
							bounds_District.top += tolerance;
							bounds_District.bottom -= tolerance;
						}
						// add feature de lay geometry
						createPolygonFromBound(vectorGraphicsClick, bounds_District);
					    
						var ii = 0;
						for (ii = 0; ii < arrFeatureDistrict.length; ii++) {
							var featureDistrict = arrFeatureDistrict[ii];
							//var b = featureDistrict.geometry.bounds;
							//if (bounds_District.intersectsBounds(b)) {
							var bb = featureDistrict.geometry.components[0];
							if (bb.intersects(vectorGraphicsClick.features[0].geometry)) {
								featureCurrentAction.attributes[arrField_Alias_Current[i].Name] = featureDistrict.attributes["dist_id"];
								for(var iInput=0;iInput<this.INPUTs.length;iInput++)
					    		{
					    			$objInputs = $(this.INPUTs[iInput]);
				    				if(this.INPUTs[iInput].toLowerCase() == "#" + arrField_Alias_Current[i].controlID.toLowerCase())
				    				{
			                            $objInputs.val(featureDistrict.attributes["name_vn"]);
				    					break;
				    				}						    			
					    		}
								break;
							}
						}
					}
					break;
				case "phuongxa":
				case "maphuong":
					if (vectorCommune != null) {
						var indexLayer = LayerTool.getIndexLayer();
						var bFeature = featureCurrentAction.geometry.bounds;
						var bounds_Commune = new OpenLayers.Bounds(bFeature.left, bFeature.bottom, bFeature.right, bFeature.top);
						if (vectorArray[indexLayer - numBaseLayer].Geometry_Type == Geometries.Point) {
							var tolerance = 1;
							bounds_Commune.left -= tolerance;
							bounds_Commune.right += tolerance;
							bounds_Commune.top += tolerance;
							bounds_Commune.bottom -= tolerance;
						}
						// add feature de lay geometry
						createPolygonFromBound(vectorGraphicsClick, bounds_Commune);
						
						var ii = 0;
						for (ii = 0; ii < arrFeatureCommune.length; ii++) {
							var featureCommune = arrFeatureCommune[ii];
							//var b = featureCommune.geometry.bounds;
							//if (bounds_Commune.intersectsBounds(b)) {
							var bb = featureCommune.geometry.components[0];
							if (bb.intersects(vectorGraphicsClick.features[0].geometry)) {
								featureCurrentAction.attributes[arrField_Alias_Current[i].Name] = featureCommune.attributes["com_id"];
								for(var iInput=0;iInput<this.INPUTs.length;iInput++)
					    		{
					    			$objInputs = $(this.INPUTs[iInput]);
				    				if(this.INPUTs[iInput].toLowerCase() == "#" + arrField_Alias_Current[i].controlID.toLowerCase())
				    				{
			                            $objInputs.val(featureCommune.attributes["name_vn"]);
				    					break;
				    				}						    			
					    		}
								break;
							}
						}
					}
					break;	
				default:					
	    			var $objInputs = $("#"+arrField_Alias_Current[i].controlID);
	    			if($objInputs.length == 0) continue;
    				objValue = base.trim($objInputs.val());
	    			if(actionCurrent == PortletTypeAction.Insert || actionCurrent == PortletTypeAction.InsertCoor) 
	    			{
		    			if((arrField_Alias_Current[i].Type == "int" || arrField_Alias_Current[i].Type == "decimal"))
	    				{
		    				
	    				}
		    			if(objValue != '') featureCurrentAction.attributes[arrField_Alias_Current[i].Name] = objValue;
		    			else
	    				{
	                    	$objInputs.val(featureCurrentAction.attributes[arrField_Alias_Current[i].Name]);
	    				}
	    			}
	    			else
    				{
                    	$objInputs.val(featureCurrentAction.attributes[arrField_Alias_Current[i].Name]);
    				}
					if(arrField_Alias_Current[i].controlID == 'txt_QHCHITIET_QHChung')
					{
						setChangedQHChiTiet_MaQHChung();						
					}
					break;
    			}
			}
    	}
    	var indexLayer = LayerTool.getIndexLayer();
    	var layerSelected = vectorArray[indexLayer - numBaseLayer];
    	switch (layerSelected.LayerId.toLowerCase()) {
		default:
	   		$("#" + assetObj.fieldsetID + " select").uniform();
			break;
    	}
    };
    
    this.disabledAll = function() {
    	var i = 0;
    	for(i=0;i<this.INPUTs.length;i++)
		{
			$input = $(this.INPUTs[i]);
			$input.attr('disabled', true);
		}    
    	for(i=0;i<this.NUMBERs.length;i++)
		{
			$input = $(this.INPUTs[i]);
			$input.attr('disabled', true);
		}    	
    	for(i=0;i<this.SELECTs.length;i++)
		{
			$input = $(this.INPUTs[i]);
			$input.attr('disabled', true);
		}    
    	for(i=0;i<this.BUTTONs.length;i++)
		{
			$input = $(this.INPUTs[i]);
			$input.attr('disabled', true);
		}    
		$('#' + this.fieldsetID + ' select').uniform();
	};
    
    this.enabledAll = function() {
    	var i = 0;
    	for(i=0;i<this.INPUTs.length;i++)
		{
			$input = $(this.INPUTs[i]);
			$input.attr('disabled', false);
		} 
    	
    	for(i=0;i<this.SELECTs.length;i++)
		{
			$input = $(this.SELECTs[i]);
			$input.attr('disabled', false);
		}    
    	for(i=0;i<this.BUTTONs.length;i++)
		{
			$input = $(this.BUTTONs[i]);
			$input.attr('disabled', false);
		}    
		$('#' + this.fieldsetID + ' select').uniform();
	};
	
    this.cancelAll = function()
    {
    	for(var i=0;i<this.INPUTs.length;i++)
		{
			$input = $(this.INPUTs[i]);
			$input.empty();
			$input.val("");
		}    	

    	for(var i=0;i<this.SELECTs.length;i++)
		{
			$input = $(this.SELECTs[i]);
			$input.attr('selectedIndex', 0);
			$input.val("0");
		}

    	for(var i=0;i<this.DATEs.length;i++)
		{
			$input = $(this.DATEs[i]);
			$input.val("");
		}
    };
    
    // point
    this.cancelButton_Point = function()
    {
    	// restore lai coordinate
    	if(this.COORDINATE != undefined)
		{
	    	if(this.COORDINATE["x"] != undefined)
			{
	    		var X = this.COORDINATE["x"];
	    		featureCurrentAction.geometry.x = parseFloat(X[0]);
			}
	    	
	    	if(this.COORDINATE["y"] != undefined)
			{
	    		var Y = this.COORDINATE["y"];
	    		featureCurrentAction.geometry.y = parseFloat(Y[0]);
			}
		}
    	var indexLayer = LayerTool.getIndexLayer();
    	map.layers[indexLayer].refresh();
    	this.cancelAll();
    	AddFeatureAttribute_Close();
		vectorGraphics.removeAllFeatures();
		
		if(actionCurrent == PortletTypeAction.InsertCoor)
		{
			//this.cancelInsertCoor_Polyline();
			this.cancelInsertCoor_Point();
		}
    };
    
    this.disabledButton = function()
    {
    	for(var i=0;i<this.BUTTONs.length;i++)
    	{
        	$(this.BUTTONs[i]).attr('disabled', true);
        	$(this.BUTTONs[i]).css('opacity', 0.3);
    	}
    };
    
    this.enabledButton = function()
    {
    	for(var i=0;i<this.BUTTONs.length;i++)
    	{
        	$(this.BUTTONs[i]).attr('disabled', false);
        	$(this.BUTTONs[i]).css('opacity', 1);
    	}
    };
    
    // disable & reset file
    this.disabledFiles = function() {
    	if(this.FILES == null) return;
    	for(var i=0;i<this.FILES.length;i++)
    	{
    		var files = this.FILES[i];
    		var form = $(files[0]); 
    		if(form.length > 0) 
			{
    			form[0].reset();
    			var input = $(files[1]);
    			input.attr('disabled', true);
			}
    	}
	};
	
    // enabled
	this.enabledFiles = function() {
    	if(this.FILES == null) return;
    	for(var i=0;i<this.FILES.length;i++)
    	{
    		var files = this.FILES[i];
    		var form = $(files[0]);
    		if(form.length > 0) 
			{
    			form[0].reset();
    			var input = $(files[1]);
    			input.attr('disabled', false);
			}
    	}
	};
	
	// tao moi tai san quy hoach
	this.newAsset = function(id)
	{
		//var maQHChung = Cookies.getCookie(QHCHUNG_COOKIE);
		/*if(maQHChung != null)
		{
			alert(LANGUAGE['msg_QHCHUNG_New']);
			return false;
		}*/
         this.STATUS_ASSET = STATUS_ASSET.INSERT;
 		 if(id != undefined) base.enabledAll(document.getElementById(id));
 		 this.enabledAll();
         this.cancelAll();
 		 // focus den truong key
 		 if(this.PKFIELDs.length > 0) $(this.PKFIELDs[0]).focus();
 		// hien div shp
 		$("#div_QHCHUNG_SHP").show();
 		$("#div_QHCHITIET_SHP").show();
 		// hien thi lai textbox nhap ma quy hoach chi tiet - an danh sach ma quy hoach
		$('#div_Map_QHChitiet_MaQH').hide();
		$('#' + assetQHCHUNG.fieldsetID + ' select').uniform();	
		$('#' + assetQHCHITIET.fieldsetID + ' select').uniform();
		actionCurrent = PortletTypeAction.Insert;
		featureCurrentAction = null;
		return true;
	};    
	
	/****** ban do quy hoach *********/
	// tao moi ban do quy hoach	
	// bActiveTab: true: active tab QH Chung
	this.newBandoQH = function(bActiveTab) {
		 if(!assetQHCHITIET.newAsset('div_Map_QHChitiet_Tabs')) return;
		 assetQHCHUNG.newAsset('div_Map_QHChung_Tabs');
		 if(!bActiveTab) return;
		 // active tab quy hoach chung
		 tabsQuyHoachObj.tabQuyhoachActive(true);	 
	};	
	
	this.loadVungQuyHoach = function() {
 		var i = 0, j = 0;
		var ulBDQH = 'ul_Map_Bandoquyhoach';
		// xoa cac node con
		var liTags = $("#" + ulBDQH).find('li');
		var iLength = liTags.length;
		while(iLength>0)
		{
			$(liTags[iLength-1]).remove();
			iLength--;
		}
		// load danh sach ban do quy hoach chung
		var layerName = this.layerName;
		var objVectorLayer = LayerTool.getVectorLayer(layerName);
 		var indexLayer = objVectorLayer.IndexLayer;
 		var objLayer = map.layers[indexLayer];
 		var feature = null;
 		var sMaQH = '';
 		var arrMaQH = [];
 		var bInsert = true;
 		trvBandoQuyHoach.soluongvungQH = objLayer.features.length;
 		if(objLayer.features.length == 0)
		{
 			setTimeout("assetQHCHUNG.loadVungQuyHoach()", 3000);
 			this.loadQHToZoom = true;
 			return;
		}
 		if(this.loadQHToZoom)
		{
			var extent = objLayer.getDataExtent();
			if (extent == null) {
	
			} else map.zoomToExtent(extent);
		}
 		
 		this.aObjQuyhoachActive = null;
 		for(i=0;i<objLayer.features.length;i++)
 		{
 			bInsert = true;
 			feature = objLayer.features[i];
 			 // add node vao tree view ban do quy hoach
 			 var maQH = feature.attributes[this.MaVungQHChungField];
 			 for(j=0;j<arrMaQH.length;j++)
			 {
 				sMaQH = arrMaQH[j];
 				if(maQH == sMaQH)
				{
 					bInsert = false;
 					break;
 				}
			 }
 			 if(bInsert)
			 {
 				 arrMaQH[arrMaQH.length] = maQH;
	 			 var sTenQH = feature.attributes["tenvungquyhoachchung"];
	 			 var sNamQH = feature.attributes["namquyhoach"];
	 			 var sTabValue = maQH + "---" + sTenQH + "---" + sNamQH;
	 			 trvBandoQuyHoach.addNodeBandoquyhoach(ulBDQH, sTenQH, maQH, sTabValue);
			 }
 		}
 		if(this.aObjQuyhoachActive != null) 
		{
 			$(this.aObjQuyhoachActive).mousedown();
		}

		//right click menu
		$(".add-edit-quyhoach li").contextMenu({
		    menu: 'contextmenuBandoquyhoach'
		});	
	};
	
	this.loadVungQHChungToCombobox = function() {
		var selectQHCHITIETQHChung = base.getElementById('select_QHCHITIET_QHChung');
		$('#select_QHCHITIET_QHChung option').each(function () {
		    $(this).remove();
		});
		// loa lop ban do QH Chung
 		var objVectorLayerQHChung = LayerTool.getVectorLayer(assetQHCHUNG.layerName);
 		var indexLayerQHChhung = objVectorLayerQHChung.IndexLayer;
 		var objLayerQHChung = map.layers[indexLayerQHChhung];
		
		// load danh sach ban do quy hoach chung 		
		var layerName = assetQHCHUNG.layerName;
		var objVectorLayer = LayerTool.getVectorLayer(layerName);
 		var indexLayer = objVectorLayer.IndexLayer;
 		var objLayer = map.layers[indexLayer];
		var i = 0, j = 0;
 		var feature = null;
 		var sMaQH = '';
 		var arrMaQH = [];
 		var bInsert = true;
		for(i=0;i<objLayerQHChung.features.length;i++)
		{
			bInsert = true;
			feature = objLayerQHChung.features[i];
			 // add node vao tree view ban do quy hoach
			 var maQH = feature.attributes[this.MaVungQHChungField];
			 for(j=0;j<arrMaQH.length;j++)
			 {
					sMaQH = arrMaQH[j];
					if(maQH == sMaQH)
					{
						bInsert = false;
						break;
					}
			 }
			 if(bInsert)
			 {
	 			// tu ma QH chung lay thongtin vung qh chung
		 		var arrFeaturQHChung = objLayerQHChung.getFeaturesByAttribute(this.MaVungQHChungField,maQH);
		 		if(arrFeaturQHChung.length > 0)
	 			{
		 			var sTenQH = arrFeaturQHChung[0].attributes["tenvungquyhoachchung"];
					var elOptNew = document.createElement('option');
					elOptNew.text = maQH; //sTenQH;
					elOptNew.value = maQH;
					try {
						// not IE
						if(selectQHCHITIETQHChung != null) selectQHCHITIETQHChung.add(elOptNew, null);
					} catch (ex) {
						// IE only
						if(selectQHCHITIETQHChung != null) selectQHCHITIETQHChung.add(elOptNew);
					}				
					 arrMaQH[arrMaQH.length] = maQH;
				 }
			 }
		}
	};
	
	this.loadVungQHChiTietToCombobox = function(maQHChung) {
		var selectQHCHITIETQHChitiet = base.getElementById('select_QHCHITIET_QHChiTiet');
		$('#select_QHCHITIET_QHChiTiet option').each(function () {
		    $(this).remove();
		});
		// lay lop ban do QH Chitiet		
 		var objVectorLayerQHChitiet = LayerTool.getVectorLayer(assetQHCHITIET.layerName);
 		var indexLayerQHChitiet = objVectorLayerQHChitiet.IndexLayer;
 		var objLayerQHChitiet = map.layers[indexLayerQHChitiet];
		var featuresQuery = objLayerQHChitiet.getFeaturesByAttribute(assetQHCHITIET.MaVungQHChungField, maQHChung);
		for(var i=0;i<featuresQuery.length;i++)
		{
			var feature = featuresQuery[i];
 			var sTenQHChitiet = feature.attributes["tenvungquyhoachchitiet"];
 			var sMaQHChitiet = feature.attributes["mavungquyhoachchitiet"];;
			var elOptNew = document.createElement('option');
			elOptNew.text = sMaQHChitiet;
			elOptNew.value = feature.fid; //sMaQHChitiet;
			try {
				// not IE
				if(selectQHCHITIETQHChitiet != null) selectQHCHITIETQHChitiet.add(elOptNew, null);
			} catch (ex) {
				// IE only
				if(selectQHCHITIETQHChitiet != null) selectQHCHITIETQHChitiet.add(elOptNew);
			}				
		}
		//$('#txt_QHCHITIET_MaQHCHITIET').hide();
		$('#div_Map_QHChitiet_MaQH').show();
		$('#div_Map_QHChitiet_MaQH select').uniform();		
		$('#select_QHCHITIET_QHChiTiet').focus();
	};
	
	this.loadInfoQHChiTiet = function(sMaQHChitiet_FID) {
		var layerName = this.layerName;
		var objVectorLayer = LayerTool.getVectorLayer(layerName);
 		var indexLayer = objVectorLayer.IndexLayer;
 		var objLayer = map.layers[indexLayer];
		
 		featureCurrentAction = objLayer.getFeatureByFid(sMaQHChitiet_FID);
		//.getFeaturesByAttribute(this.MaVungQGChitietField, sMaQHChitiet);
		//if(arrFeaturQHChung.length == 0) return;
 		//var feature = arrFeaturQHChung[0];
 		//featureCurrentAction = feature;
 		vectorGraphics.removeAllFeatures();
		createPolygonFromGeometry(vectorGraphics, featureCurrentAction.geometry);
 		
		var i = 0;
		for (i = 0; i < this.AliasName.length; i++){
 			var sControlID = this.AliasName[i].controlID;
 			var objValue = featureCurrentAction.attributes[this.AliasName[i].Name];
 			if(this.AliasName[i].Type == 'date' && objValue != undefined)
			{
 				// format: yyyy-mm-dd
 				objValue = objValue.split('-');
 				if(objValue.length == 3)
				{
	 				// format: dd/mm/yyyy
	 				objValue = objValue[2] + '/' + objValue[1] + '/' + objValue[0];
	 				$('#' + sControlID).datepicker('setDate', objValue);
				}
			}
 			else $('#' + sControlID).val(objValue);
 			this.AttrInfoQH[this.AliasName[i].Name] = objValue;
 		}	 	
	};
	
	this.delBDQH = function() {
		if(assetQHCHUNG.MaQHChung == '')
		{
			alert(LANGUAGE['msg_del_select_vungqh']);
			return;
		}
		this.STATUS_ASSET = STATUS_ASSET.DELETE;
        var r=confirm(LANGUAGE["msg_delete"]);
        if (r)
        {
        	var i = 0;
        	var objVectorLayer = null;
        	var indexLayer = 0;
        	var objLayer = null;
    		var sMaQHChung = assetQHCHUNG.MaQHChung;
    		/*** xoa quy hoach chi tiet ****/
     		objVectorLayer = LayerTool.getVectorLayer(assetQHCHITIET.layerName);
     		indexLayer = objVectorLayer.IndexLayer;
     		objLayer = map.layers[indexLayer];
     		// lay danh sach cac feature
	 		var arrFeaturQHChitiet = objLayer.getFeaturesByAttribute(this.MaVungQHChungField,sMaQHChung);
    		// xoa feature tren map
	 		for(i=0; i<arrFeaturQHChitiet.length;i++)
 			{
	 			arrFeaturQHChitiet[i].style = {visibility: 'hidden'};
	 			arrFeaturQHChitiet[i].style.display = 'none';
	    		featureRemoveFromLayer(arrFeaturQHChitiet[i], objLayer);	
 			}
	 		MapAction.SaveActionByIndexLayer(indexLayer);
    		/***************************/
    		/*** xoa quy hoach chung ***/
     		objVectorLayer = LayerTool.getVectorLayer(assetQHCHUNG.layerName);
     		indexLayer = objVectorLayer.IndexLayer;
     		objLayer = map.layers[indexLayer];
     		// lay danh sach cac feature
	 		var arrFeaturQHChung = objLayer.getFeaturesByAttribute(this.MaVungQHChungField,sMaQHChung);
    		// xoa feature tren map
	 		for(i=0; i<arrFeaturQHChung.length;i++)
 			{
	 			arrFeaturQHChung[i].style = {visibility: 'hidden'};
	 			arrFeaturQHChung[i].style.display = 'none';
	    		featureRemoveFromLayer(arrFeaturQHChung[i], objLayer);	
 			}
	 		// save data
	 		MapAction.SaveActionByIndexLayer(indexLayer);
	 		// liet ke lai danh sach vung quy hoach
            alert(LANGUAGE["msg_BDQHCHung_Del_Success"]);
	 		this.loadVungQuyHoach();
    		/***************************/
      	}
	};
	/********************************************/
	
	// su kien them doi tuong bang cach nhap toa do
	this.insertCoor_Point = function()
	{
		var XCoor = base.trim($("#txt_Map_InserCoor_Point_XCoor").val());
		var YCoor = base.trim($("#txt_Map_InserCoor_Point_YCoor").val());
		if(XCoor=="" || YCoor=="")
		{
			alert(LANGUAGE["msg_insertcoor_inputpoint"]);
			$("#txt_Map_InserCoor_Point_XCoor").focus();
			return;
		}
		
		// xac dinh layer dang chon
		var indexLayer = LayerTool.getIndexLayer();
		var layerAsset = map.layers[indexLayer];
		
		// tao moi 1 feature tuong ung voi toa do nhap
		var pPoint = new OpenLayers.Geometry.Point();
		pPoint.x = parseFloat(XCoor);
		pPoint.y = parseFloat(YCoor);
		var pointFeature = new OpenLayers.Feature.Vector(pPoint, null, null);
		featureCurrentAction = pointFeature;		
		layerAsset.redraw(true);
		layerAsset.addFeatures([ featureCurrentAction ]);
		featureCurrentAction = layerAsset.features[layerAsset.features.length - 1];
		featureCurrentAction.state = OpenLayers.State.INSERT;
		// fill du lieu vao
		var evt = new Object();
		evt.feature = featureCurrentAction;
		event_featureadded(evt);
		
		// dong cua so
		$(divMapInserCoorWindowPoint).fadeOut(300);

		// focus den truong key
		if(assetCurrent.PKFIELDs.length > 0) $(assetCurrent.PKFIELDs[0]).focus();
	};
	
	this.cancelInsertCoor_Point = function()
	{
		// xac dinh layer dang chon
		if(featureCurrentAction!=null) featureRemove(featureCurrentAction);
		
		// dong cua so
		$(divMapInserCoorWindowPoint).fadeOut(300);
	}; 
	
	// su kien them doi tuong bang cach nhap toa do diem dau - diem cuoi cho line
	this.insertCoor_Polyline = function()
	{
		var XCoor1 = base.trim($("#txt_Map_InserCoor_Polyline_XCoor1").val());
		var YCoor1 = base.trim($("#txt_Map_InserCoor_Polyline_YCoor1").val());
		var XCoor2 = base.trim($("#txt_Map_InserCoor_Polyline_XCoor2").val());
		var YCoor2 = base.trim($("#txt_Map_InserCoor_Polyline_YCoor2").val());
		if(XCoor1=="" || YCoor1=="" || XCoor2=="" || YCoor2=="")
		{
			alert(LANGUAGE["msg_insertcoor_inputpoint"]);
			$("#txt_Map_InserCoor_Polyline_XCoor1").focus();
			return;
		}

		// xac dinh layer dang chon
		var indexLayer = LayerTool.getIndexLayer();
		var layerAsset = map.layers[indexLayer];
		
		var pPoint1 = new OpenLayers.Geometry.Point();
		pPoint1.x = parseFloat(XCoor1);
		pPoint1.y = parseFloat(YCoor1);
		//var pointFeature1 = new OpenLayers.Feature.Vector(pPoint1, null, null);

		var pPoint2 = new OpenLayers.Geometry.Point();
		pPoint2.x = parseFloat(XCoor2);
		pPoint2.y = parseFloat(YCoor2);
		//var pointFeature2 = new OpenLayers.Feature.Vector(pPoint2, null, null);
		
		var pointList = [];
		pointList.push(pPoint1);
		pointList.push(pPoint2);
		var line = new OpenLayers.Geometry.LineString(pointList);
		var mline = new OpenLayers.Geometry.MultiLineString(line);
		var style = {
			strokeColor : colorSelectedLineDelete,
			strokeOpacity : 0.8,
			strokeWidth : 3
		};

		var lineFeature = new OpenLayers.Feature.Vector(mline, null, style);
		featureCurrentAction = lineFeature;
		layerAsset.redraw(true);
		layerAsset.addFeatures([ featureCurrentAction ]);		
		featureCurrentAction = layerAsset.features[layerAsset.features.length - 1];
		featureCurrentAction.state = OpenLayers.State.INSERT;
		// fill du lieu vao
		assetType = new Asset_Type.init();
		var evt = new Object();
		evt.feature = featureCurrentAction;
		event_featureadded(evt);
		
		// dong cua so
		$(divMapInserCoorWindowPolyline).fadeOut(300);

		// focus den truong key
		if(assetCurrent.PKFIELDs.length > 0) $(assetCurrent.PKFIELDs[0]).focus();
	};
	
	this.cancelInsertCoor_Polyline = function()
	{
		// xac dinh layer dang chon
		if(featureCurrentAction!=null) featureRemove(featureCurrentAction);
		
		// dong cua so
		$(divMapInserCoorWindowPolyline).fadeOut(300);;
	}; 
	
	/******* tim thua dat tu sohieuthua & sôtbando **************/
	this.getThuadatFromSohieuthua_Soto = function(sohieuthuadat, soto) {
		// getFeaturesByAttribute
		if(sohieuthuadat == undefined || soto == undefined) 
		{
			//alert('chon thong tin thua dat');
			return;
		}
		var layerThuadat = map.layers[LayerTool.getVectorLayer(assetTHUADAT.layerName).IndexLayer];
		var arrThuadat = layerThuadat.getFeaturesByAttribute('sohieuthuadat', sohieuthuadat);;
		var thuadat = null;
		var i = 0, feature = null;
		for(i=0; i<arrThuadat.length; i++)
		{
			feature = arrThuadat[i];
			if(feature && feature.attributes['soto'] == soto)
			{
				thuadat = feature;
				break;
			}
		}
		if(thuadat == null)
		{
			//alert('ko co thua dat nao duoc tim thay');
			return;
		}
		//thuadat.drawFeature(thuadat, 'select');
		vectorGraphics_Search.removeAllFeatures();
		createPolygonFromGeometry(vectorGraphics_Search, thuadat.geometry);
		/**** ve diem trong tam cua da giac *******/			
		var pointArrayComponents = thuadat.geometry.components[0].components[0].components;
		var pointArray = [];
		for(i=0; i< pointArrayComponents.length; i++)
		{
			var point = pointArrayComponents[i];
			var pointXY = new pointVectorDecac(point.x, point.y);
			pointArray[pointArray.length] = pointXY;
		}

		vectorTool.PointArrays = pointArray;
		var pointG = vectorTool.trongtamDaGiac(pointArray.length);
		/*var style = {
				strokeColor : '#FF0000',
				strokeOpacity : "0.8",
				strokeWidth : 1,
				fillColor : '#FF0000',
				pointRadius : 2,
				cursor : "pointer"
			};
		createPointFromCoordinate(vectorGraphics_Search, pointG.x, pointG.y, style);*/
        // add feature
		var indexLayerDCP = LayerTool.getVectorLayer(assetDIEMCAPPHEP.layerName).IndexLayer;
		var layerDiemCP = map.layers[indexLayerDCP];
		// kiem tra xem co DCP ung voi sohieuthuadat -soto chua?
		var arrDiemcapphep = layerDiemCP.getFeaturesByAttribute('lodatthua', sohieuthuadat);;
		var diemcapphep = null;
		var i = 0, feature = null;
		for(i=0; i<arrDiemcapphep.length; i++)
		{
			feature = arrDiemcapphep[i];
			if(feature && feature.attributes['tothuabando'] == soto)
			{
				diemcapphep = feature;
				break;
			}
		}
		if(diemcapphep != null)
		{
			//alert('da ton tai diem cap phep');
			return;
		}
		
		var pPoint = new OpenLayers.Geometry.Point();
		pPoint.x = pointG.x;
		pPoint.y = pointG.y;
		var attributesDCP = [];
		attributesDCP['lodatthua'] = sohieuthuadat;
		attributesDCP['tothuabando'] = soto;
        var feature = new OpenLayers.Feature.Vector(pPoint, attributesDCP);
        feature.state = OpenLayers.State.INSERT;
        layerDiemCP.addFeatures([feature]);
	};
	
	this.clickAsset = function() {
		$("#ul_Map_QuanLyDQT li a").mousedown(function() {
			$(this).css('color','#0000ff');
			$(this).parent().siblings().each(function(){
				$(this).find('a').css('color','#000000');
			});
		});
	};
};

function setImg(idForm, idFileInput, idDivPreview, NameAttr_Img, Editor_Img)
{
	var formImg = $(idForm)[0];
	formImg.method = "post";
	formImg.enctype="multipart/form-data";
	formImg.action= sPortletJSP + "process_upload.jsp?server=" + serverName + "&portlet_jsp=" + sPortletJSP;
	var inputTextAlias = $(idFileInput)[0];
	inputTextAlias.type = 'file';
	inputTextAlias.accept = "image/*";
	inputTextAlias.attribute = NameAttr_Img;
	inputTextAlias.disabled = !Editor_Img;
		
	var divPreview = $(idDivPreview)[0];
	if (featureCurrentAction != null) {
		var objValue = null;
		objValue = featureCurrentAction.attributes[NameAttr_Img];
		if(objValue != null && objValue != '')
		{
			$(divPreview).html('');
			var src = sPortletImg + "Asset/" + objValue;
			var objImg = document.createElement("img");
			objImg.style.width = "32px";
			objImg.style.height = "32px";
			objImg.src = src;			
			divPreview.appendChild(objImg);	
		}
		else $(divPreview).html('');
	}
	
	// event
	var attributeName = NameAttr_Img;
	objImgUpload_Description[attributeName] = divPreview;
	$(inputTextAlias).live('change', function () {
    	var sPortlet = sPortletImg + "loader.gif";
        $(divPreview).html('');
        $(divPreview).html('<img src="' + sPortlet + '" alt="Uploading...."//>');
        $(formImg).ajaxForm({
            target: idDivPreview
        }).submit();
    });
}

function setDocument(idForm, idFileInput, idDivPreview, NameAttr_Doc)
{
	var formImg = $(idForm)[0];
	if(formImg == null) return;
	formImg.method = "post";
	formImg.enctype="multipart/form-data";
	formImg.action= sPortletJSP + "asset/asset_upload_document.jsp?server=" + serverName + "&portlet_jsp=" + sPortletJSP;
	var inputTextAlias = $(idFileInput)[0];
	inputTextAlias.type = 'file';
	//inputTextAlias.accept = "image/*";
	inputTextAlias.attribute = NameAttr_Doc;
		
	var divPreview = $(idDivPreview)[0];
	if (featureCurrentAction != null) {
		var objValue = null;
		objValue = featureCurrentAction.attributes[NameAttr_Doc];
		if(objValue != null && objValue != '')
		{
			$(divPreview).hide();
			$(divPreview).text(objValue);
			var fileName = objValue;
			$(divPreview).parent().find('a').show();
			$(divPreview).parent().find('a').attr('href',
					'/AnGiang-557-portlet/html/giamsatmoitruong/document/' + fileName);
					//'/AnGiang-557-portlet/html/giamsatmoitruong/asset/asset_download_document.jsp?filename=' + fileName);
		}
		else 
		{
			$(divPreview).hide();
			$(divPreview).html('');
			$(divPreview).parent().find('a').hide();
		}
	}

	// event
	var attributeName = NameAttr_Doc;
	objDivUpload_Description[attributeName] = divPreview;
	$(inputTextAlias).live('change', function () {
    	var sPortlet = sPortletImg + "loader.gif";
		$(divPreview).show();
        $(divPreview).html('');
        $(divPreview).html('<img src="' + sPortlet + '" alt="Uploading...."//>');
        $(formImg).ajaxForm({
            target: idDivPreview,
        	success: function (response) {
    			//alert('ok');
        		$(divPreview).hide();
        	}
        }).submit();
    });
}

/********** tai san hien tai ************/
var assetCurrent = null;

/********** quy hoach chung ************/
var assetQHCHUNG = new ARRAY_ASSET();

/********** quy hoach chi tiet ************/
var assetQHCHITIET = new ARRAY_ASSET();

/********** quy hoach chung - shapefile ************/
var assetQHCHUNG_SHP = new ARRAY_ASSET();

/********** quy hoach chi tiet - shapefile ************/
var assetQHCHITIET_SHP = new ARRAY_ASSET();

/********** diem cap phep ************/
var assetDIEMCAPPHEP = new ARRAY_ASSET();

/********** diem vi pham *************/
var assetDIEMVIPHAM = new ARRAY_ASSET();

/********** chi gioi duong do ********/
var assetCHIGIOIDUONGDO = new ARRAY_ASSET();

/********** chi gioi xay dung ********/
var assetCHIGIOIXAYDUNG = new ARRAY_ASSET();

/********** thua dat ********/
var assetTHUADAT = new ARRAY_ASSET();

/********** hien tran su dung dat ************/
var assetHTSDD_SHP = new ARRAY_ASSET();

/****** ban do quy hoach *****/
function addQuyhoachchung() {
	if(!validNamQH()) return;
	var bInsert = false;
	 if(assetQHCHUNG.STATUS_ASSET == STATUS_ASSET.INSERT && $("#div_QHCHUNG_SHP").css('display') != 'none') bInsert = true;	 
	// lay so luong fature
	 var objFeature = null;
	 if(bInsert)
	 {
		objFeature = $("#divPreview_Map_BandoquyhoachChung_ImageUpload_Action").text().split('&');
		assetQHCHUNG.NumFeatureQHChung = objFeature.length - 1;
		if(assetQHCHUNG.NumFeatureQHChung == 0)
		{
			alert(LANGUAGE["msg_QHCHUNG_NoFeature"]);
			return;
		}
	 }
	 else
	 {
		 assetQHCHUNG.NumFeatureQHChung = 1; // feature current dc ve tren map
		 if(actionCurrent == PortletTypeAction.Edit && featureCurrentAction != null) assetQHCHUNG.AttrInfoQH = featureCurrentAction.attributes;
	 }
	var i = 0, j = 0;
	for ( i = 0; i < assetQHCHUNG.AliasName.length; i++) {
		if (assetQHCHUNG.AliasName[i].IsRequire) // && !assetQHCHUNG.AliasName[i].IsPrimaryKey) 
		{
			var objValue = assetQHCHUNG.AttrInfoQH[assetQHCHUNG.AliasName[i].Name];
			if(objValue == null || objValue == undefined || objValue == '')
			{
				alert(assetQHCHUNG.AliasName[i].Alias + " " + LANGUAGE["msg_have_data"]);
				$("#" + assetQHCHUNG.AliasName[i].controlID).focus();
				return false;
			}
		}
	}

	for ( i = 0; i < assetQHCHUNG.AliasName.length; i++) {
		if(assetQHCHUNG.AliasName[i].Type == 'file')
		{
			var attribute = assetQHCHUNG.AliasName[i].Name;
			var divObj = objDivUpload_Description[attribute];
			// truong hop co thay doi tep
			if(divObj != undefined) featureCurrentAction.attributes[attribute] = $(divObj).text();
		}
	}
	
	// lay layer
	var objVectorLayer = LayerTool.getVectorLayer(assetQHCHUNG.layerName);
	var indexLayer = objVectorLayer.IndexLayer;
	var objLayer = map.layers[indexLayer];
	if(bInsert)
	{
		// neu them moi thi cap lai shape va attributes
		for(i = 0;i<objFeature.length;i++)
		{
			var objGeoms = objFeature[i].split('|');
			if(objGeoms.length <2) continue;
			objGeoms = objGeoms[1];
			var points = [];
			// cap toa do (x, y) dc tach nhau boi dau ;
			objGeoms = objGeoms.split(';');
			for(j=0;j<objGeoms.length;j++)
			{
				var objCoor = objGeoms[j].split(',');
				if(objCoor.length<2) continue;
				var xCoor = objCoor[0];
				var yCoor = objCoor[1];
				var point = new OpenLayers.Geometry.Point(xCoor, yCoor);
				points[points.length] = point;
			}
	        var ring = new OpenLayers.Geometry.LinearRing(points);
	        var polygon = new OpenLayers.Geometry.Polygon([ring]);
	        var multyPolygon = new OpenLayers.Geometry.MultiPolygon(polygon);
	        // add feature
	        var feature = new OpenLayers.Feature.Vector(multyPolygon, assetQHCHUNG.AttrInfoQH);
	        feature.state = OpenLayers.State.INSERT;
	        objLayer.addFeatures([feature]);
		}
	}
	else
	{
		// truong hop them moi bang ve doi tuong
		if($("#div_QHCHUNG_SHP").css('display') == 'none' && featureCurrentAction != null)
		{
			featureCurrentAction.attributes = assetQHCHUNG.AttrInfoQH;
			if(actionCurrent == PortletTypeAction.Edit) featureCurrentAction.state = OpenLayers.State.UPDATE;
			else featureCurrentAction.state = OpenLayers.State.INSERT;
		}
		else
		{
			// neu update thi chi cap nhat attribute 
			var objMaQHChung = $("#txt_QHCHUNG_MaQHCHUNG").val();    
	 		var arrFeaturQHChung = objLayer.getFeaturesByAttribute(assetQHCHUNG.MaVungQHChungField,objMaQHChung);
	 		var iLength = arrFeaturQHChung.length;
	 		for(i=0;i<iLength;i++)
			{
	 			var feature = arrFeaturQHChung[i];
	 			feature.attributes = assetQHCHUNG.AttrInfoQH;
	 			feature.state = OpenLayers.State.UPDATE;
			}
		}
	}
	objLayer.refresh();
	alert(LANGUAGE["msg_QHCHUNG_Update_Success"]);
	// save data
	MapAction.SaveActionByIndexLayer(indexLayer);
	// disabled 2 nut
	if(actionCurrent == PortletTypeAction.Insert)
	{
		$("#btn_QHCHUNG_Update").attr('disabled', true);
		$("#btn_QHCHUNG_Cancel").attr('disabled', true);	
	}
	
	// thiet lap ma vung quy hoach chung cho quy hoach chi tiet
	var objMaQHChung = $("#txt_QHCHUNG_MaQHCHUNG").val();    
	$("#txt_QHCHITIET_QHChung").val(objMaQHChung);
	$("#txt_QHCHITIET_QHChung").attr('disabled', true);
	$("#txt_QHCHITIET_MaQHCHITIET").focus();
	for ( i = 0; i < assetQHCHITIET.AliasName.length; i++) {
		var controlID = assetQHCHITIET.AliasName[i].controlID;
		if(controlID.toLowerCase() == "txt_QHCHITIET_QHChung".toLowerCase())
		{
			assetQHCHITIET.AttrInfoQH[assetQHCHITIET.AliasName[i].Name] = objMaQHChung;
			break;
		}
	}
	assetQHCHITIET.MaQHChung = objMaQHChung;
	if(bInsert)
	{
		// add node vao tree view ban do quy hoach
		var sMaQH = $("#txt_QHCHUNG_TenQHCHUNG").val();
		var sTenQH = $("#txt_QHCHUNG_TenQHCHUNG").val();
		var sNamQH = $("#txt_QHCHUNG_NamQH").val();
		var sTabValue = sMaQH + "---" + sTenQH + "---" + sNamQH; 
		trvBandoQuyHoach.addNodeBandoquyhoach('ul_Map_Bandoquyhoach', sTenQH, sMaQH, sTabValue);
	}
	
	if(actionCurrent == PortletTypeAction.Edit) return;
	// active tab quy hoach chi tiet
	tabsQuyHoachObj.tabQuyhoachActive(false);
}

function addQuyhoachchitiet() {
	if(!validNamQH()) return;
	var bInsert = false;
	 if(assetQHCHUNG.STATUS_ASSET == STATUS_ASSET.INSERT && $("#div_QHCHITIET_SHP").css('display') != 'none') bInsert = true;	 
	// lay so luong fature
	 var objFeature = null;
	 if(bInsert)
	 {
 		// lay so luong fature
 		objFeature = $("#divPreview_Map_BandoquyhoachChitiet_ImageUpload_Action").text().split('&');
 		assetQHCHITIET.NumFeatureQHChiTiet = objFeature.length - 1;
 		if(assetQHCHITIET.NumFeatureQHChiTiet == 0)
 		{
 			alert(LANGUAGE["msg_QHCHITIET_NoFeature"]);
 			return;
 		}
	 }
	 else
	 {
		 assetQHCHITIET.NumFeatureQHChiTiet = 1;
		 if(actionCurrent == PortletTypeAction.Edit) assetQHCHITIET.AttrInfoQH= featureCurrentAction.attributes;
	 }
	var i = 0, j = 0;
	for ( i = 0; i < assetQHCHITIET.AliasName.length; i++) {
		if (assetQHCHITIET.AliasName[i].IsRequire) // && !assetQHCHITIET.AliasName[i].IsPrimaryKey) 
		{
			var objValue = assetQHCHITIET.AttrInfoQH[assetQHCHITIET.AliasName[i].Name];
			if(objValue == null || objValue == undefined || objValue == '')
			{
				alert(assetQHCHITIET.AliasName[i].Alias + " " + LANGUAGE["msg_have_data"]);
				$("#" + assetQHCHITIET.AliasName[i].controlID).focus();
				return false;
			}
		}
	}

	for ( i = 0; i < assetQHCHITIET.AliasName.length; i++) {
		if(assetQHCHITIET.AliasName[i].Type == 'file')
		{
			var attribute = assetQHCHITIET.AliasName[i].Name;
			var divObj = objDivUpload_Description[attribute];
			// truong hop co thay doi tep
			if(divObj != undefined) featureCurrentAction.attributes[attribute] = $(divObj).text();
		}
	}
	
	// lay layer
	var objVectorLayer = LayerTool.getVectorLayer(assetQHCHITIET.layerName);
	var indexLayer = objVectorLayer.IndexLayer;
	var objLayer = map.layers[indexLayer];
	//lay thong tin thuoc tinh
	var attrInfo = assetQHCHITIET.AttrInfoQH;
	if(bInsert)
	{
		// neu them moi thi cap lai shape va attributes
 		for(i = 0;i<objFeature.length;i++)
 		{
 			var objGeoms = objFeature[i].split('|');
 			if(objGeoms.length <2) continue;
 			objGeoms = objGeoms[1];
 			var points = [];
 			// cap toa do (x, y) dc tach nhau boi dau ;
 			objGeoms = objGeoms.split(';');
 			for(j=0;j<objGeoms.length;j++)
 			{
 				var objCoor = objGeoms[j].split(',');
 				if(objCoor.length<2) continue;
 				var xCoor = objCoor[0];
 				var yCoor = objCoor[1];
 				var point = new OpenLayers.Geometry.Point(xCoor, yCoor);
 				points[points.length] = point;
 			}
 	        var ring = new OpenLayers.Geometry.LinearRing(points);
 	        var polygon = new OpenLayers.Geometry.Polygon([ring]);
 	        var multyPolygon = new OpenLayers.Geometry.MultiPolygon(polygon);
 	        // add feature
 	        var feature = new OpenLayers.Feature.Vector(multyPolygon, assetQHCHITIET.AttrInfoQH);
 	        feature.state = OpenLayers.State.INSERT;
 	        objLayer.addFeatures([feature]);
 		}
	}
	else
	{
		// truong hop them moi bang ve doi tuong
		if($("#div_QHCHUNG_SHP").css('display') == 'none')
		{
			featureCurrentAction.attributes = assetQHCHITIET.AttrInfoQH;
			if(actionCurrent == PortletTypeAction.Edit) featureCurrentAction.state = OpenLayers.State.UPDATE;
			else featureCurrentAction.state = OpenLayers.State.INSERT;
		}
		else
		{
			// neu update thi chi cap nhat attribute
			var objMaQHChiTiet = $("#txt_QHCHITIET_MaQHCHITIET").val();
	 		var arrFeaturQHChiTiet = objLayer.getFeaturesByAttribute("mavungquyhoachchitiet",objMaQHChiTiet);
	 		var iLength = arrFeaturQHChiTiet.length;
	 		for(i=0;i<iLength;i++)
			{
	 			var feature = arrFeaturQHChiTiet[i];
	 			feature.attributes = assetQHCHITIET.AttrInfoQH;
	 			feature.state = OpenLayers.State.UPDATE;
			}
		}
	}
	objLayer.refresh();
	
	alert(LANGUAGE["msg_QHCHITIET_Update_Success"]);
	// save data
	MapAction.SaveActionByIndexLayer(indexLayer);
	// disabled 2 nut
	if(actionCurrent == PortletTypeAction.Insert)
	{
		$("#btn_QHCHITIET_Update").attr('disabled', true);
		$("#btn_QHCHITIET_Cancel").attr('disabled', true);
	}
	
	// load lai vung quy hoach
	loadQuyHoach();
}	

function setChangedQHChiTiet_MaQHChung()
{
	$("#select_QHCHITIET_QHChung").val($("#txt_QHCHITIET_QHChung").val());
	$("#form_QHCHITIET_mapleft_menu select").uniform();
}

function validNamQH() {
	var namBatdau = '';
	var namKetthuc = '';
	if(base.trim($('#txt_QHCHITIET_NamQH').val()) == '') return true;
	if(base.trim($('#txt_QHCHUNG_TGBD').val()) != '') namBatdau = base.trim($('#txt_QHCHUNG_TGBD').val()); 
	if(base.trim($('#txt_QHCHUNG_TGKT').val()) != '') namKetthuc = base.trim($('#txt_QHCHUNG_TGKT').val());
	
	var namQH = parseInt($('#txt_QHCHITIET_NamQH').val());
	var namBD = -1;
	if(namBatdau != '') namBD = $('#txt_QHCHUNG_TGBD').datepicker('getDate').getFullYear();
	var namKT = -1;
	if(namKetthuc != '') namKT = $('#txt_QHCHUNG_TGKT').datepicker('getDate').getFullYear();
	if(namBD < namQH && namBD != -1)
	{
		alert(LANGUAGE['msg_QHCHUNG_NamBD_QH']);
		$('#txt_QHCHUNG_TGBD').focus();
		return false;
	}
	if(namKT < namQH && namKT != -1)
	{
		alert(LANGUAGE['msg_QHCHUNG_NamKT_QH']);
		$('#txt_QHCHUNG_TGKT').focus();
		return false;
	}
	if(namBD > namKT && namBD != -1 && namKT != -1)
	{
		alert(LANGUAGE['msg_QHCHUNG_NamBD_KT']);
		$('#txt_QHCHUNG_TGBD').focus();
		return false;
	}
	return true;
}